import webconst from '@/utils/webconst.js'
// socket.js
let socketTask = null;
let isConnected = false;
let heartbeatInterval = null;
let connectLimitCount = 3;
let currentconnectLimitCount = 0;
let _goupId="";
let _userId="";
let _nickName="";
let _onMessageCallback=null;
export function connectWebSocket(groupId,userId,nickName,onMessageCallback) {
	console.log('socket connect')
	if(isConnected)
	{
		
		console.log("socket connected so not connect again")
		return;
	}
	// 关闭旧连接
	if (socketTask) {
		socketTask.close();
	}
    _goupId=groupId;
	_userId=userId;
	_nickName=nickName;
	_onMessageCallback=onMessageCallback
	socketTask = uni.connectSocket({
		url: webconst.base_socket_url+`?groupId=`+groupId+`&userId=`+userId+`&nickName=`+nickName,
		success: () => {
			console.log('socket connect successs');
		}
	});

	// 监听打开
	socketTask.onOpen(() => {
		console.log('socket open');
		isConnected = true;
		let ping = JSON.stringify({
			type: "ping"
		});
		// 启动心跳
		heartbeatInterval = setInterval(() => {
			socketTask.send({
				data: ping,
				success: () => {
					console.log('ping success');
				}
			});
		}, 30 * 1000); // 每30秒一次心跳 
	});

	// 监听消息
	socketTask.onMessage((res) => {
		console.log(res.data);
		const data = JSON.parse(res.data);

		// 处理不同消息类型
		switch (data.type) {
			case 'pong':
				console.log('socket received pong');
				break;
			case 'message':
				// 例如：聊天消息
				console.log('socket received message:', data.message);
				 if (typeof onMessageCallback === 'function') {
				          onMessageCallback(data.message); // 把消息数据传给外部函数
				}
				// 触发全局事件或 Vuex 提交
				uni.showToast({
					title: data.message,
					duration: 2000,
					icon: 'none',          // 不显示图标
					position: 'bottom'     // 显示在底部
				});
				break;
			case 'notice':
				// 系统通知
				uni.showModal({
					title: '通知',
					content: data.message
				});
				break;
		}
	});

	// 监听错误
	socketTask.onError((err) => {
		console.error('socket error:', err);
		reconnect();
	});

	// 监听关闭
	socketTask.onClose(() => {
		console.log('socket close');
		isConnected = false;
		clearInterval(heartbeatInterval);
		//reconnect(); // 可选：自动重连
	});
}

// 发送消息
export function sendMessage(content) {
	if (!isConnected) return;
	console.log("send msg content:" + content);
	socketTask.send({
		data: JSON.stringify({
			type: "message",
			content: content
		}),
		success: () => {
			console.log('send message sucess')
		},
		fail: (error) => {
			console.log('send message err' + error)
		}
	});
}



// 重连机制
function reconnect() {
	setTimeout(() => {
		if (!isConnected) {
			if (currentconnectLimitCount > connectLimitCount) {
				return;
			}
			currentconnectLimitCount = currentconnectLimitCount + 1;
			console.log('socket reconnect' + currentconnectLimitCount);
			console.log('socket  reconnect...');
			connectWebSocket(_goupId,_userId,_nickName,_onMessageCallback);
		}
	}, 3000); // 10秒后重试
}

// 关闭连接
export function closeWebSocket() {
	console.log('client close socket')
	if (socketTask) {
		socketTask.close();
	}
	clearInterval(heartbeatInterval);
}